<!--组件：-->
<template>
  <div>
    <a-link @click="openDrawer">编辑</a-link>

    <a-modal
      :visible="visible"
      title="编辑"
      :width="720"
      @cancel="closeDrawer"
      @ok="validate"
    >
      <a-spin :loading="loading">
        <a-form ref="formRef" :model="form" :style="{ width: '600px' }">
          <a-row :gutter="24">
            <a-col>
              <a-form-item
                label="模板名称"
                field="excelName"
                :rules="[{ required: true, message: '请输入模板名称' }]"
              >
                <a-input v-model="form.excelName" />
              </a-form-item>
            </a-col>
            <a-col>
              <a-form-item label="备注" field="remark">
                <a-textarea v-model="form.remark" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>

      <a-button
        :disabled="isEditing"
        style="margin-bottom: 10px"
        @click="addRow"
      >
        <template #icon>
          <icon-plus />
        </template>
        新增
      </a-button>
      <a-table
        :columns="COLUMNS"
        :data="list"
        :loading="loadingList"
        :pagination="false"
      >
        <template #columnName="{ record, rowIndex }">
          <a-input v-if="record.editing" v-model="list[rowIndex].columnName" />
          <span v-else>{{ list[rowIndex].columnName }}</span>
        </template>
        <template #columnOrder="{ record, rowIndex }">
          <a-input-number
            v-if="record.editing"
            v-model="list[rowIndex].columnOrder"
            :min="0"
          />
          <span v-else>{{ list[rowIndex].columnOrder }}</span>
        </template>
        <template #operation="{ record }">
          <a-space v-if="record.editing">
            <a-link @click="saveRow(record)">保存</a-link>
            <a-link @click="cancelEdit(record.id)">取消</a-link>
          </a-space>
          <a-space v-else-if="!isEditing">
            <a-link @click="editRow(record.id)">编辑</a-link>
            <a-link @click="removeRow(record)">删除</a-link>
          </a-space>
          <a-space v-else>
            <a-link disabled>编辑</a-link>
            <a-link disabled>删除</a-link>
          </a-space>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts" name="PropertyEdit">
  import { ref, computed } from 'vue';
  import { TableColumnData, Message } from '@arco-design/web-vue';
  import { ExcelPropertyRecord } from '@/api/infrastructure/model/excelModuleModel';
  import {
    getExcelModuleById,
    updateExcelModuleRecord,
    queryExcelProperties,
    saveExcelPropertyRecord,
    updateExcelPropertyRecord,
    removeExcelPropertyRecord,
  } from '@/api/infrastructure/excel-module';

  interface PropertyRow extends ExcelPropertyRecord {
    editing?: boolean;
    isNew?: boolean;
  }

  const props = defineProps({
    moduleId: { type: String, required: true },
  });
  const visible = ref<boolean>(false);
  const openDrawer = () => {
    getModuleById();
    getPropertiesByModuleId();
    visible.value = true;
  };
  const closeDrawer = () => {
    list.value = [];
    visible.value = false;
  };

  const loading = ref<boolean>(false);

  const form = ref<{ excelName: string; remark: string }>({
    excelName: '',
    remark: '',
  });
  const getModuleById = async () => {
    loading.value = true;
    try {
      const { data } = await getExcelModuleById(props.moduleId);
      form.value = {
        excelName: data.excelName || '',
        remark: data.remark || '',
      };
    } finally {
      // empty
      loading.value = false;
    }
  };
  const loadingList = ref<boolean>(false);
  const getPropertiesByModuleId = async () => {
    loadingList.value = true;
    try {
      const { data } = await queryExcelProperties(props.moduleId);
      list.value = data;
    } finally {
      loadingList.value = false;
    }
  };

  const COLUMNS: TableColumnData[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      width: 100,
      render: ({ rowIndex }) => rowIndex + 1,
      fixed: 'left',
    },
    {
      title: '列序号',
      dataIndex: 'columnOrder',
      slotName: 'columnOrder',
      align: 'center',
    },
    {
      title: '列名',
      dataIndex: 'columnName',
      slotName: 'columnName',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      slotName: 'operation',
      align: 'center',
      width: 120,
      fixed: 'right',
    },
  ];

  const list = ref<PropertyRow[]>([]);
  const addRow = () => {
    const isNew: PropertyRow = {
      id: new Date().getTime().toString(),
      columnName: '',
      columnOrder: 0,
      moduleId: props.moduleId,
      editing: true,
      isNew: true,
    };
    cacheList.value = list.value;
    list.value = [...list.value, isNew];
  };
  // 删除指定id行
  const removeRow = async (row: PropertyRow) => {
    if (row.isNew) {
      // 如果是新增行，直接删除
      list.value = list.value.filter((elem) => elem.id !== row.id);
    } else {
      // 否则需要调用接口更新
      try {
        await removeExcelPropertyRecord(row.id);
        list.value = list.value.filter((elem) => elem.id !== row.id);
      } finally {
        // empty
      }
    }
  };
  const saveRow = async (row: PropertyRow) => {
    try {
      const { moduleId, columnName, columnOrder, isNew, id } = row;
      if (isNew) {
        // 新增
        const { data } = await saveExcelPropertyRecord({
          moduleId,
          columnName,
          columnOrder,
        });
        const newList = list.value.map((elem) => {
          if (elem.id === id) {
            return {
              ...row,
              id: data,
              editing: false,
              isNew: false,
            };
          }
          return elem;
        });
        list.value = newList;
      } else {
        // 更新字段
        await updateExcelPropertyRecord({
          id,
          moduleId,
          columnName,
          columnOrder,
        });
        const newList = list.value.map((elem) => {
          if (elem.id === id) {
            return {
              ...row,
              editing: false,
            };
          }
          return elem;
        });
        list.value = newList;
      }
    } finally {
      // empty
    }
  };
  // 表格中是否有数据正在编辑
  // 有任意数据在编辑中都不可以同时编辑第二条
  const isEditing = computed(() => {
    return !!list.value.find((elem) => elem.editing);
  });
  const cacheList = ref<PropertyRow[]>([]);
  const editRow = (id: string) => {
    const newList = list.value.map((elem) => {
      if (elem.id === id) {
        return {
          ...elem,
          editing: true,
        };
      }
      return elem;
    });
    cacheList.value = list.value;
    list.value = newList;
  };
  const cancelEdit = (_id: string) => {
    list.value = cacheList.value;
  };

  const emits = defineEmits(['afterSubmit']);
  const formRef = ref<any>();
  const validate = async () => {
    const errors = await formRef.value.validate();
    if (!errors) {
      updateModule();
    }
  };
  const updateModule = async () => {
    try {
      await updateExcelModuleRecord({
        ...form.value,
        id: props.moduleId,
      });
      Message.success('修改成功');
      closeDrawer();
    } finally {
      emits('afterSubmit');
    }
  };
</script>
